import { jwtDecode } from "jwt-decode";
import { useStore } from "vuex";
import axios from "axios";

const ModuleUser = {
  state: {
    //存数据
    username: "",
    photo: "",
    access_token: "",
    refresh_token: "",
    is_login: false,
  },
  getters: {
    // 数据计算获取
    getCurrentUsername: (state) => {
      return state.username;
    },
    getCurrentStatus: (state) => {
      return state.is_login;
    },
  },
  mutations: {
    // vue中mutations不能执行异步操作
    // 对state中存储数据的修改
    updateUser(state, user) {
      state.username = user.username;
      state.photo = user.photo;
      state.access_token = user.access_token;
      state.refresh_token = user.refresh_token;
      state.is_login = user.is_login;
      let loginUser = {
        username: user.username,
        photo: user.photo,
        access_token: user.access_token,
        refresh_token: user.refresh_token,
        is_login: user.is_login,
      };
      localStorage.setItem("localUser", JSON.stringify(loginUser));
    },
    updateAccess(state, access_token) {
      state.access_token = access_token;
    },
    logout(state) {
      state.username = "";
      state.photo = "";
      state.access_token = "";
      state.refresh_token = "";
      state.is_login = false;
    },
  },
  actions: {
    // 对state中存储数据的操作, 也可调用mutations的函数
    login(context, pdata) {
      axios
        .post(
          "/api/web/login",
          { username: pdata.username, password: pdata.password },
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded", // 设置 Content-Type 为表单
            },
          }
        )
        .then((response) => {
          const { access_token, refresh_token, token_type } = response.data;
          if (token_type === "error") {
            console.log(token_type);
            pdata.error();
            console.log(token_type);
            return;
          }
          const access_obj = jwtDecode(access_token);
          console.log(access_obj); // {sub: 'liang', exp: 1722940954}
          // 创建 URLSearchParams 对象 用于post直接传递字符串参数
          const searchParams = new URLSearchParams();
          searchParams.append("refresh_token", refresh_token);

          setInterval(
            () => {
              axios
                .post(`/api/web/refresh?${searchParams.toString()}`)
                .then((resp) => {
                  const { access_token, token_type } = response.data;
                  context.commit("updateAccess", access_token);
                });
            },
            5 * 60 * 1000
          ); // 5 * 60 秒发送一次 refresh 请求获取新的 access_token

          // 如果还有其他用户相关信息这里应查询数据库获取用户其它信息后更新
          let loginUser = {
            username: access_obj.sub,
            photo: "",
            access_token: access_token,
            refresh_token: refresh_token,
            is_login: true,
          };
          context.commit("updateUser", loginUser);
          pdata.success(); // 回调注册成功的函数
        })
        .catch((error) => {
          console.log(error);
          pdata.error();
        });
    },
  },
  modules: {
    // 管理和分割大量的 state
  },
};
export default ModuleUser;
